from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.mixins import ListModelMixin, UpdateModelMixin, DestroyModelMixin, CreateModelMixin
from roles.models import Role
from roles.serializers import RoleSerializer


class RoleView(GenericViewSet, ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin):
    queryset = Role.objects.all().order_by('-id')
    serializer_class = RoleSerializer
    permission_classes = [IsAuthenticated]


class SetRoleView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        # 获取参数
        rid = request.data.get('rid')
        mid = request.data.get('mid')

        if not all([rid, mid]):
            return Response({'msg': '参数不全!'}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)

        role = Role.objects.filter(id=rid).first()
        if not role:
            return Response({'msg': '角色不存在!'}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        if not isinstance(mid, list):
            return Response({'msg': '格式错误!必须为列表且列表中的元素为字符串!'},
                            status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        try:
            role.menus.set(mid)
            role.save()
            serializer = RoleSerializer(role)
            return Response({'msg': '添加角色成功', 'data': serializer.data})
        except Exception as e:
            print(e)
            return Response({'msg': '添加角色失败!'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class DelRolePermissionView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, rid, mid):
        # 获取参数
        role = Role.objects.filter(id=rid).first()
        if not role:
            return Response({'msg': '角色不存在!'}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        if mid not in [item.id for item in role.menus.all()]:
            return Response({'msg': '该角色没有该权限!', 'code': '422'}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        role.menus.remove(mid)
        role.save()
        return Response({'msg': '删除角色下的权限成功!', 'data': RoleSerializer(role).data}, status=status.HTTP_200_OK)
